﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace DJY.Code.Helper
{
    public static  class EnumHelper
    {
        /// <summary>
        /// 根据值得到中文备注
        /// </summary>
        /// <param name="e"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public static String GetEnumDesc(this Type e, int? value)
        {
            try
            {
                FieldInfo[] fields = e.GetFields();
                for (int i = 1, count = fields.Length; i < count; i++)
                {
                    if ((int)System.Enum.Parse(e, fields[i].Name) == value)
                    {
                        DescriptionAttribute[] EnumAttributes = (DescriptionAttribute[])fields[i].
                    GetCustomAttributes(typeof(DescriptionAttribute), false);
                        if (EnumAttributes.Length > 0)
                        {
                            return EnumAttributes[0].Description;
                        }
                    }
                }
                return "";
            }
            catch (Exception)
            {
                return "";

            }
        }

        public static List<EnumberCreditType> EnumToList<T>()
        {
            List<EnumberCreditType> list = new List<EnumberCreditType>();

            foreach (var e in Enum.GetValues(typeof(T)))
            {
                EnumberCreditType m = new EnumberCreditType();
                object[] objArr = e.GetType().GetField(e.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), true);
                if (objArr != null && objArr.Length > 0)
                {
                    DescriptionAttribute da = objArr[0] as DescriptionAttribute;
                    m.Desction = da.Description;
                }
                //SetClassification 
                //object[] setClassificationArr = e.GetType().GetField(e.ToString()).GetCustomAttributes(typeof(SetClassificationAttribute), true);
                //if (setClassificationArr != null && setClassificationArr.Length > 0)
                //{
                //    //SetClassificationAttribute da = setClassificationArr[0] as SetClassificationAttribute;
                //    //m.Classification = da.Type;
                //}
                //Display
                object[] disArr = e.GetType().GetField(e.ToString()).GetCustomAttributes(typeof(DisplayNameAttribute), true);
                if (disArr != null && disArr.Length > 0)
                {
                    DisplayNameAttribute da = disArr[0] as DisplayNameAttribute;
                    m.Name = da.DisplayName;
                }

                m.Value = Convert.ToInt32(e);
                m.Key = e.ToString();
                list.Add(m);
            }
            return list;
        }
    }
}
